using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using RBAC.ErrorCode;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement.H;

namespace RBAC.Write.Api.Controllers.ERP
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DeliveryNoticeAuditController : ControllerBase
    {
        private readonly IMediator _mediator;

        public DeliveryNoticeAuditController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 更新发货通知单状态：0=开立(反审核)、1=审核、2=退回
        /// </summary>
        [HttpPost]
        public Task<APIResult<bool>> ApproveOrReturn([FromBody] ApproveOrReturnDeliveryNoticeCommand request, CancellationToken cancellationToken)
        {
            // 从 Claims 解析当前登录用户ID（兼容多种常见 ClaimType）
            long? uid = null;
            var user = HttpContext?.User;
            if (user?.Identity?.IsAuthenticated == true)
            {
                string? idStr = user.FindFirstValue(ClaimTypes.NameIdentifier)
                                 ?? user.FindFirstValue("sub")
                                 ?? user.FindFirstValue("userId")
                                 ?? user.FindFirstValue("UserId")
                                 ?? user.FindFirstValue("uid");
                if (long.TryParse(idStr, out var parsed))
                {
                    uid = parsed;
                }
            }

            // 仅当从 Claims 解析到用户ID时覆盖，否则保留请求体传入的 AuditUserId 以便在无鉴权环境下测试
            if (uid.HasValue)
            {
                request.AuditUserId = uid.Value;
            }
            return _mediator.Send(request, cancellationToken);
        }
    }
}
